<script setup>
import {onMounted, onUnmounted, ref} from 'vue'

const canvas = ref(null);

function resize() {
  canvas.value.width = window.innerWidth;
  canvas.value.height = window.innerHeight;
}

let stop;

onMounted(function () {
  resize();
  const canvas_dom = canvas.value;

  const ctx = canvas_dom.getContext("2d");

  const numStars = 800;
  const radius = "0." + Math.floor(Math.random() * 9) + 1;
  const focalLength = canvas_dom.width * 2;
  const warp = 0;
  let centerX, centerY;

  let stars = [],
    star;
  let i;

  initializeStars();

  (function executeFrame() {
    stop = window.requestAnimationFrame(executeFrame);
    moveStars();
    drawStars();
  }());

  function initializeStars() {
    centerX = canvas_dom.width / 2;
    centerY = canvas_dom.height / 2;

    stars = [];
    for (i = 0; i < numStars; i++) {
      star = {
        x: Math.random() * canvas_dom.width,
        y: Math.random() * canvas_dom.height,
        z: Math.random() * canvas_dom.width,
        o: "0." + Math.floor(Math.random() * 99) + 1
      };
      stars.push(star);
    }
  }

  function moveStars() {
    for (i = 0; i < numStars; i++) {
      star = stars[i];
      star.z--;

      if (star.z <= 0) {
        star.z = canvas_dom.width;
      }
    }
  }

  function drawStars() {
    let pixelX, pixelY, pixelRadius;

    // Resize to the screen
    if (
      canvas_dom.width !== window.innerWidth ||
      canvas_dom.width !== window.innerWidth
    ) {
      canvas_dom.width = window.innerWidth;
      canvas_dom.height = window.innerHeight;
      initializeStars();
    }
    if (warp === 0) {
      ctx.fillStyle = "rgba(0,10,20,1)";
      ctx.fillRect(0, 0, canvas_dom.width, canvas_dom.height);
    }
    ctx.fillStyle = "rgba(209, 255, 255, " + radius + ")";
    for (i = 0; i < numStars; i++) {
      star = stars[i];

      pixelX = (star.x - centerX) * (focalLength / star.z);
      pixelX += centerX;
      pixelY = (star.y - centerY) * (focalLength / star.z);
      pixelY += centerY;
      pixelRadius = (focalLength / star.z);

      ctx.fillRect(pixelX, pixelY, pixelRadius, pixelRadius);
      ctx.fillStyle = "rgba(209, 255, 255, " + star.o + ")";
      // ctx.fill();
    }
  }
});

onUnmounted(function () {
  cancelAnimationFrame(stop)
});

</script>

<template>
  <teleport to="body">
    <canvas class="lottery-background" ref="canvas">您的浏览器不支持canvas</canvas>
  </teleport>
</template>

<style scoped>

canvas.lottery-background {
  position: fixed;
  z-index:  -999;
  top:      0;
  left:     0;
}
</style>
